package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"path/filepath"
	"time"
	"zg5/zk1/goods-management/api-gateway/internal/request"
	"zg5/zk1/goods-management/common/global"
	"zg5/zk1/goods-management/common/proto/goods"
	"zg5/zk1/goods-management/pkg"
)

func AddGoods(c *gin.Context) {

	var req request.AddGoodsReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}

	_, err := global.GoodsGrpc.AddGoods(c, &goods.AddGoodsRequest{
		Images:      req.Images,
		Name:        req.Name,
		TypesId:     req.TypesId,
		StockpileId: req.StockpileId,
		K:           req.K,
		V:           req.V,
		Price:       req.Price,
		Stockpile:   req.Stockpile,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "商品发布成功",
		"data": nil,
	})
	return
}

func GoodsList(c *gin.Context) {

	var req request.GoodsListReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}

	goodsList, err := global.GoodsGrpc.GoodsList(c, &goods.GoodsListRequest{
		Page:    req.Page,
		Size:    req.Size,
		Status:  req.Status,
		KeyWord: req.KeyWord,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "商品列表展示成功",
		"data": goodsList,
	})
	return
}

func OssUpload(c *gin.Context) {
	// 单文件
	file, _ := c.FormFile("file")

	ext := filepath.Ext(file.Filename)

	filename := time.Now().Format("20060102150405") + ext

	dst := "./static/img/" + filename
	// 上传文件至指定的完整文件路径
	err := c.SaveUploadedFile(file, dst)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	imgUrl := pkg.OssUpload(filename, dst)
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "图片上传成功",
		"data": imgUrl,
	})
	return
}
